﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Slippor.Douban.Radio.Share;

namespace Slippor.Douban.Radio.BaseForm.CustomControls
{
    public partial class ShareToolStripMenuItem : ToolStripMenuItem, IShareContainer
    {
        private readonly Dictionary<String, ToolStripMenuItem> _shareItems = new Dictionary<string, ToolStripMenuItem>();

        public ShareToolStripMenuItem()
        {
            InitializeComponent();

        }

        public void Add(ISharer share)
        {
            var shareItem = new ToolStripMenuItem(share.Name) { Tag = share, CheckOnClick = false, };
            shareItem.Click += shareItem_Click;
            DropDownItems.Add(shareItem);
            _shareItems.Add(share.Name, shareItem);
            share.PreShare += (sender,e) =>
                {
                    shareItem.Text = StringResource.Share_Sharing;
                    shareItem.Enabled = false;
                };
            share.PostShare += (sender, e) =>
                {
                    shareItem.Text = share.Name;
                    shareItem.Enabled = true;
                    if((e.Error != null && !(bool)e.Result) && share.ErrorAlert)
                    {
                        MessageBox.Show(String.Format(StringResource.Share_ShareFailed, share.Name, e.Error.Message));
                    }
                };
        }

        public void Remove(ISharer share)
        {
            DropDownItems.Remove(_shareItems[share.Name]);
            _shareItems.Remove(share.Name);
        }

        private void shareItem_Click(object sender, EventArgs e)
        {
            var shareItem = sender as ToolStripMenuItem;
            if (shareItem != null)
            {
                var share = shareItem.Tag as ISharer;
                if (share != null)
                {
                    share.Share();
                }
            }
        }
    }
}
